{% extends 'base.html' %}
{% block title %}Deployment{% endblock %}
{% block item-2 %}layui-nav-itemed{% endblock %}
{% block item-2-1 %}layui-this{% endblock %}
{% block context %}

   <span class="layui-breadcrumb">
        <a href="#">首页</a>
        <a href="#">Kubernetes</a>
        <a><cite>Deployment</cite></a>
    </span>
    <hr>
    <div class="layui-card">
        {% csrf_token %}
        <div class="layui-card-body">
            <div class="layui-row">
                <div class="layui-col-md12">
                    <a href="{% url 'deployment_create' %}" class="layui-btn" style="float: left;margin-right: 10px" id="createDP">创建</a>
                    <input type="text" name="name" lay-verify="title" placeholder="请输入名称" class="layui-input" style="width: 150px;float: left">
                    <button class="layui-btn" id="searchBtn" style="float: left">搜索</button>
                </div>

                <div class="layui-col-md12">
                    <table id="demo" lay-filter="test"></table>
                    <!--  行工具 -->
                    <script type="text/html" id="barDemo">
                      <a class="layui-btn layui-btn-xs layui-btn-primary" lay-event="yaml">YAML</a>
                      <a class="layui-btn layui-btn-xs" lay-event="details">详情</a>
                      <a class="layui-btn layui-btn-xs" lay-event="scale">扩容/缩容</a>
                      <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
                    </script>
                </div>

            </div>
        </div>
    </div>

{% endblock %}
{% block custom_js %}
<script>
    // 获取当前命名空间
    var storage = window.sessionStorage;
    var namespace = storage.getItem('namespace');

  layui.use('table', function(){
  var table = layui.table;
  var $ = layui.jquery;

  table.render({
    elem: '#demo' // 选择table元素
    ,url: '{% url 'deployment_api' %}?namespace=' + namespace //数据接口, namespace值从当前session中获取
    ,page: true //开启分页
    ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
    ,defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
         title: '提示'
        ,layEvent: 'LAYTABLE_TIPS'
        ,icon: 'layui-icon-tips'
      }]
    ,cols: [[ //表头
      {field: 'name', title: '名称', sort: true}
      ,{field: 'namespace', title: '命名空间'}
      ,{field: 'replicas', title: '预期副本数'}
      ,{field: 'available_replicas', title: '可用副本数'}
      ,{field: 'labels', title: '标签',templet: labelsFormat}
      ,{field: 'selector', title: 'Pod标签选择器',templet: selectorFormat}
      ,{field: 'containers', title: '容器', templet: containersFormat}
      ,{field: 'create_time', title: '创建时间'}
      ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:250}
    ]],
    id: 'TT',
  });

      // 标签格式化
      function labelsFormat(d) {
          result = "";
          for(key in d.labels) {
              result += '<span style="border: 1px solid lightgrey;border-radius: 5px">' + key + ': ' + d.labels[key] + '</span><br>'
          }
          return result
      }
      // 标签选择器格式化
      function selectorFormat(d) {
          console.log(d)
          result = "";
          for(key in d.selector) {
              result += '<span style="border: 1px solid lightgrey;border-radius: 5px">' + key + ': ' + d.selector[key] + '</span><br>'
          }
          return result
      }

      function containersFormat(d) {
          result = "";
          for(key in d.containers) {
              result += key + '=' + d.containers[key] + '<br>'
          }
          return result
      }

     //监听行工具事件
    table.on('tool(test)', function(obj){
      var data = obj.data;
      var csrf_token = $('[name="csrfmiddlewaretoken"]').val();
      if(obj.event === 'del'){
        layer.confirm('真的要删除吗？', function(index){
          $.ajax({
             type: "DELETE",
              url: "{% url 'deployment_api' %}",
              data: data,
              headers: {'X-CSRFToken': csrf_token},  // 放到请求头，django也会验证这字段
              success: function (result) {
                  if (result.code == '0') {
                      obj.del();  // 临时删除当前页面记录
                      layer.msg(result.msg, {icon: 6})
                  } else {
                      layer.msg(result.msg, {icon: 5})
                  }
              },
              error: function () {
                  layer.msg("服务器接口异常！", {icon: 5})
              }
          });

          layer.close(index);
        });
      } else if(obj.event === 'yaml'){
            layer.open({
                title: "YAML",
                type: 2, // 内嵌层，从另一个网址加载
                area: ['50%', '60%'],
                content: '{% url "ace_editor" %}?resource=deployment&' + 'namespace=' + data['namespace'] + '&name=' + data['name']
            })
      } else if(obj.event === 'details'){
            window.location.href="{% url 'deployment_details' %}?namespace=" + data['namespace'] + '&name=' + data["name"]
      } else if(obj.event === 'scale'){
             layer.prompt({
                formType: 0
                ,value: data.replicas   // 默认值，从当前字段获取
              }, function(value, index){
                csrf_token = $('[name="csrfmiddlewaretoken"]').val();
                data['replicas']=value;  // value是表单输入的值，重置值
                $.ajax({
                    url: '{% url "deployment_api" %}',
                    type: "PUT",
                    data: data,
                    headers: {"X-CSRFToken": csrf_token},
                    success: function (res) {
                         if(res.code == '0'){
                               layer.msg(res.msg,{icon:6}); //2秒关闭（如果不配置，默认是3秒）
                               // 更新当前页面字段值
                               obj.update({
                                   replicas: value
                               })
                           } else {
                               layer.msg(res.msg, {icon:5})
                           }
                    }
                });
                layer.close(index);  // 关闭弹窗
              });
      }
    });
    // 监听搜索事件
    $(document).on('click','#searchBtn', function () {
        var input_val = $('.layui-input').val();
       // var input_val = $("input[name='name']").val();
        table.reload('TT', {
            where: {   //设定异步数据接口的额外参数，任意设置
                search_key: input_val
            },
            page: {
                curr: 1  //重新从第 1 页开始
            }
        })
    })
});
</script>

{% endblock %}